package com.greateamd.timetableasy.client.mvc.view.crud.course;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.greateamd.timetableasy.client.mvc.model.Model;
import com.greateamd.timetableasy.client.services.course.CourseService;
import com.greateamd.timetableasy.client.services.course.CourseServiceAsync;
import com.greateamd.timetableasy.client.services.util.ServerCall;
import com.greateamd.timetableasy.domain.Course;
import com.greateamd.timetableasy.domain.User;

public class AddCoursePage <M extends Model> extends IAddCoursePage<M>{

	private final CourseServiceAsync courseService = GWT.create(CourseService.class);

	@UiTemplate("AddCoursePage.ui.xml")
	interface AddCoursePageUIBinder extends UiBinder<Widget, AddCoursePage> {}
	private static AddCoursePageUIBinder uiBinder = GWT.create(AddCoursePageUIBinder.class);
	
	@UiField TextBox name;
	@UiField TextBox type;
	@UiField Button submitBt;
	
	/**
	 * Constructor
	 */
	public AddCoursePage() {
	    initWidget(uiBinder.createAndBindUi(this));
	}
	
	public Widget getWidgetPage() {
		return this;
	}

	@Override
	public void setUser(User user) {
	}


	//---------------------------------------------------------------------
	//-------------------------- UI action

	
	//---------------------------------------------------------------------
	//-------------------------- Handler

	@UiHandler("submitBt")
	void onSubmitBtClick(ClickEvent e){
		addCourse();
	}
	
	//---------------------------------------------------------------------
	//-------------------------- Server call
	
	private void addCourse() {
		new ServerCall<Boolean>() {

			@Override
			protected void callService(AsyncCallback<Boolean> asyncCallback) {
				Course c = new Course(name.getText(), type.getText(),null,null,null);
				courseService.save(c,asyncCallback);
			}

			@Override
			public void onSuccess(Boolean success) {
				Window.alert("Success " +success);
				//TODO: Could return to a menu
			}
		}.call();
	}
}
